package com.nexgo.payment.trans.detail;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.nexgo.payment.R;
import com.nexgo.payment.adapter.TransListAdapter;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.fragment.ProgressDialogFragment;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.ui.BaseActivity;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.RecyclerDivider;
import com.nexgo.payment.widget.TitleBuilder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import java8.util.Optional;

/**
 * 交易列表界面
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月14日
 */
public class TransListActivity extends BaseActivity implements TransListContract.View, View.OnClickListener, TransListAdapter.OnItemClickListener {
    private static final String TAG = TransListActivity.class.getSimpleName();
    private static final int REQ_CODE = 1000;
    private static final int RESP_CODE = 2000;
    private static final String IS_CHANGE = "isChange";

    @BindView(R.id.et_voucher_no)
    EditText etVoucherNo;
    @BindView(R.id.rv_trans_list)
    RecyclerView rvTransList;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;

    private Context mContext;
    private boolean isLoading;
    private LinearLayoutManager mLayoutManager;
    private TransListAdapter mListAdapter;
    private List<TransRecord> mTransList;
    private TransListPresenter mPresenter;
    private Handler mHandler = new Handler();
    private ProgressDialogFragment mDialogFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans_list);
        ButterKnife.bind(this);

        mContext = this;
        new TransListPresenter(this, Repository.getInstance());

        initView();
        initEvent();
        initData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        new TitleBuilder(this)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
//                .setRightText(getString(R.string.trans_list_print_detail))
                .setTitleText(getString(R.string.trans_list_title))
                .build();
    }

    /**
     * 绑定事件
     */
    private void initEvent() {
        //监听滑动事件
        rvTransList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int totalItemCount = mListAdapter.getItemCount();
                int lastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition();
                if (!isLoading && totalItemCount == (lastVisibleItemPosition + 1) && totalItemCount > 4) {
                    //这里加载更多数据
                    mHandler.postDelayed(() -> mPresenter.getMoreTransList(), 1000);
                    isLoading = true;
                }
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mLayoutManager = new LinearLayoutManager(this);
        rvTransList.setLayoutManager(mLayoutManager);
        rvTransList.addItemDecoration(new RecyclerDivider(this, 15, RecyclerDivider.HORIZONTAL));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //首次加载数据
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left, R.id.iv_search, R.id.title_tv_right})
//    @OnClick({R.id.title_iv_left, R.id.iv_search})
    @Override
    public void onClick(View view) {
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_iv_left:
                finish();
                break;
            case R.id.iv_search:
                //查询
                mPresenter.getTransRecord(etVoucherNo.getText().toString());
                break;
            case R.id.title_tv_right:
                mPresenter.printDetail();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(int position) {
        if (mTransList == null || position == mTransList.size()) {
            return;  //防止点击上下页时闪退
        }
        //跳转到订单详情页面
        TransRecord transRecord = mTransList.get(position);
//        startActivityForResult(TransDetailActivity.newInstance(mContext, transRecord.getTraceNum()), REQ_CODE);
        startActivityForResult(TransDetailActivity.newInstance(mContext, transRecord.getTraceNum(),true), REQ_CODE);
        //startActivity(TransDetailActivity.newInstance(mContext, transRecord.getTraceNum()));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE && resultCode == RESP_CODE){
            Bundle bundle = data.getExtras();
            if (bundle != null && bundle.getBoolean(IS_CHANGE, false)){
                mPresenter.refreshTransList();
            }
        }
    }

    @Override
    public void setPresenter(TransListPresenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onTransList(List<TransRecord> transList, boolean isSearch) {
        if (mTransList == null) {
            mTransList = new ArrayList<>();
        }
        //搜索时返回一个交易记录，先清除之前的交易记录
        if (transList.size() == 1 && mTransList.size() != 0 && isSearch) {
            mTransList.clear();
        }
        mTransList.addAll(transList);
        if (mListAdapter == null) {
            mListAdapter = new TransListAdapter(mContext);
            rvTransList.setAdapter(mListAdapter);
            mListAdapter.setOnItemClickListener(this);
        }
        mListAdapter.addTransList(mTransList);
        //移除上拉加载更多视图
        mListAdapter.notifyItemRemoved(mListAdapter.getItemCount());
        isLoading = false;
    }

    @Override
    public void showClearList() {
        if (mTransList != null && !mTransList.isEmpty()){
            mTransList.clear();
        }
        if (mListAdapter != null){
            mListAdapter.clear();
        }
        rvTransList.removeAllViews();
    }

    @Override
    public void showNotMoreData() {
        ToastUtils.showToast(getString(R.string.has_no_more_data));
        //移除上拉加载更多视图
        mListAdapter.notifyItemRemoved(mListAdapter.getItemCount());
        isLoading = false;
    }

    @Override
    public void showEmptyList() {
        rvTransList.setVisibility(View.GONE);
        ivEmpty.setVisibility(View.VISIBLE);
    }

    @Override
    public void showEmptyItem() {
        ToastUtils.showToast(getString(R.string.trace_num_not_exsit));
    }

    @Override
    public void showEmptyInput() {
        ToastUtils.showToast(getString(R.string.input_can_no_be_empty));
    }

    @Override
    public void showErrInput() {
        ToastUtils.showToast(getString(R.string.err_input));
    }

    @Override
    public void setPrintingIndicator(boolean active) {
        if (active) {
            if (mDialogFragment == null) {
                mDialogFragment = new ProgressDialogFragment();
            }
            mDialogFragment.setTipTitle(getString(R.string.printing));
            mDialogFragment.setTip(getString(R.string.printing_detail_can_cancel));
            mDialogFragment.setCancelable(false);
            mDialogFragment.show(getSupportFragmentManager(), null);
            mDialogFragment.setOnDialogListener(() -> mPresenter.cancelPrintDetail());
        } else {
            if (mDialogFragment != null && mDialogFragment.getDialog() != null) {
                Dialog dialog = mDialogFragment.getDialog();
                if (dialog.isShowing()) {
                    mDialogFragment.dismiss();
                }
                mDialogFragment = null;
            }
        }
    }

    @Override
    public void showPrintLackPaper() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.print_lack_paper));
        dialogFragment.setContentText(getString(R.string.print_lack_desc), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                mPresenter.cancelPrintDetail();
            }

            @Override
            public void onConfirm() {
                mPresenter.continuePrintDetail();
            }
        });
        dialogFragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void showPrintFail(String failDesc) {
        Optional.ofNullable(failDesc)
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> ToastUtils.showToast(s));
    }
}
